# coding:utf-8
__author__ = 'admin zhoushuang'
__date__ = '2016/9/28'

import base64
import os
from base_handler import *
from common_functions import *


class mod_uploadfile(BaseHandler):
    """ Receive file from remote terminal, and stored it on local disk.

    The file is encoded by base64.
    Request Parameters:
        module      = mod_uploadfile
        filename    = ...               # the file name
        storepath   = ...               # local stored dir, absolut path
        base64      = ...               # content encoded by base64
    """

    def __init__(self):
        super(mod_uploadfile, self).__init__()
        pass

    def handle(self, reqdict):
        try:
            param = extract_param(reqdict, (('filename', 1), ('storepath', 1), ('base64', 1)))
        except ValueError:
            self.echo.write('#ERROR req param error, reqdict = {} \n'.format(reqdict))
            return
        lpath = param['storepath']
        if os.path.exists(lpath) and os.path.isdir(lpath) and os.path.isabs(lpath):
            pass
        elif lpath.startswith('/') and not os.pathisdir():
            # os.mkdir(lpath)
            os.makedirs(lpath)
        lpath = lpath + os.sep + os.path.basename(param['filename'])
        with open(lpath, 'wt') as f:
            # f.write(param['base64'])
            f.write(base64.b64decode(param['base64']))

    def handle_request_side(self, reqdict, address_tuple):
        filepath = reqdict.get('filename', None)
        if filepath is None:
            print '#Error, filename is not set'
            raise ValueError()
        if os.path.isfile(filepath):
            with open(filepath, 'rb') as f:
                byts = f.read()
                b64 = base64.b64encode(byts)
                reqdict['base64'] = b64
                print sendrequest(address_tuple, reqdict)
        else:
            print '#Error {} is not a file.'.format(filepath)


def gethandler():
    return gethandler.cache


gethandler.cache = mod_uploadfile()